package middleware

import (
	"github.com/duke-git/lancet/v2/slice"
	"github.com/gin-gonic/gin"

	"gin-api-server/core_library/global"
	"gin-api-server/core_library/library/webengine/resp"
	"gin-api-server/utils"
)

func BackendMiddleware() gin.HandlerFunc {

	return func(c *gin.Context) {

		url := c.Request.URL.Path
		if !slice.Contain(global.NONEEDAUTHMETHOD, url) {
			authorization := c.GetHeader("Authorization")
			if len(authorization) == 0 {
				resp.Response(c, 401, "鉴权失败", "--")
				c.Abort()
				return
			}
			userId := utils.JwtToken{}.Decode(authorization)
			if userId <= 0 {
				resp.Response(c, 401, "鉴权失败", "--")
				c.Abort()
				return
			}
			c.Set("admin_user_id", userId)
		}

		c.Next()
	}

}
